function Note(title,time,text){ 
    this.title = title; 
    this.time = time;
    this.tag=new Object();
    this.text=text;
}

function Notebook(title){
    this.title=title;
    this.contents=new Object();
}

function Tag(tag_name){
    this.name=tag_name;
    this.notes=new Object();
}

function request(method,url,obj,func){
    var httpRequest = new XMLHttpRequest();
    httpRequest.open(method, url, true); 
    httpRequest.setRequestHeader("Content-type","application/json");
    httpRequest.send(JSON.stringify(obj));
    httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            var res = httpRequest.responseText;
            func(res);
        }
    };
}

function new_notebook(){
    let title=prompt("请键入笔记本名称","");
    if(title){
        if(arr_selection[0].indexOf(title)!==-1){
            alert('该笔记本已存在！');
            return;
        }
        let book=new Notebook(title);
        request('POST','/notebook',book);
        setTimeout(function() {
            window.location.href='/view/note-program/index.html';
        }, 100);
    }
    else return;
}

function open_notebook(title){
    let book=new Notebook(title);
    let href='/notebook?title='+title;
    request('GET',href,null,(res)=>{
        let notes=JSON.parse(res)[0]['contents'];
        let book_title=JSON.parse(res)[0]['title'];
        let html='';
        let notes_length=0;
        if(notes!==undefined){
            notes_length=notes.length;
            notes.forEach((item)=>{
                let tag=item.tags;
                let tag_html=`<div class="tag-item" onclick="add_tags('${book_title}','${item.title}');" id="tag_button">+标签</div>`;
                if(tag!==undefined){
                        tag.forEach((t)=>{
                        tag_html=`<div class="tag-item">${t}</div>`+tag_html;
                    })
                }
                if(window.screen.width>651){
                    html+=`
                    <div class="note-info-summary" onclick="view_note('${book_title}','${item.title}');">
                        <h4>${item.title}</h4>
                        <div class="tags">
                            ${tag_html}
                        </div>
                        <p class="time">${item.time}</p>
                    </div>    
                    `
                }
                else{
                    html+=`
                    <div id="span">
                        <div class="note-info-summary" onclick="start_edit('${book_title}','${item.title}');">
                            <h4>${item.title}</h4>
                            <div class="tags">
                                ${tag_html}
                            </div>
                            <p class="time">${item.time}</p>
                        </div> 
                        <div class="del"></div>
                    </div>
                    `
                }
            })
        }
        document.getElementById('all-notes').innerHTML=html;
        document.getElementById('note-navi').innerHTML=`
            <p id="header">${book_title}</p>
            <div class="note-add">
                <p id="number">共${notes_length}条笔记</p>
                <p id="add" onclick="create_new_note('${book_title}');">新建笔记</p>
            </div>
            <div class="box">
	            <input type="text" class="input" placeholder="请输入您要搜索的笔记或标签" id="search_input">
	            <input type="button" value="search" class="button" onclick="search_note('${book_title}')">
            </div>
        `;
        if(window.screen.width<650){
            let aLi=document.querySelectorAll('#span');
            for(let i=0;i<aLi.length;i++){
                aLi[i].addEventListener("touchstart", function (e,i) {
                console.log('touchstart');
                timer = setTimeout(function () {
                     console.log('LongPress');
                     e.preventDefault();
                     let del=window.confirm('确认删除该笔记？');
                     if(del){
                        let x=e.path[1].onclick+'';
                        let r = /["|'](.*)["|']/;
                        let ans=x.match(r)[0]+'';
                        ans=ans.split(",")
                        delete_note(eval(ans[0]),eval(ans[1]));//将笔记放入回收站
                     }
                }, 800);
            });
            aLi[i].addEventListener("touchmove", function (e) {
                console.log('touchmove');
                clearTimeout(timer);
                timer = 0;
            });
            aLi[i].addEventListener("touchend", function (e) {
                console.log('touchend');
                clearTimeout(timer);
                if (timer != 0) {
                    // alert('这是点击，不是长按');
                }
                return false;
            });
          }
        }
    });
}

function search_note(book_title){
    let search=document.getElementById('search_input');
    let note_title=search.value;
    let href='/notebook?title='+book_title;
    request('GET',href,null,(res)=>{
        let notes=JSON.parse(res)[0]['contents'];
        let html='';
        let notes_length=0;
        if(notes!==undefined){
            notes.forEach((item)=>{
                let cnt=0;
                let tag=item.tags;
                if(item.title.indexOf(note_title)!=-1) cnt++;
                let tag_html=`<div class="tag-item" onclick="add_tags('${book_title}','${item.title}');" id="tag_button">+标签</div>`;
                if(tag!==undefined){
                        tag.forEach((t)=>{
                        tag_html=`<div class="tag-item">${t}</div>`+tag_html;
                        if(t.indexOf(note_title)!=-1) cnt++;
                    })
                }
                if(cnt){
                    notes_length++;
                    if(window.screen.width>651){
                    html+=`
                    <div class="note-info-summary" onclick="view_note('${book_title}','${item.title}');">
                        <h4>${item.title}</h4>
                        <div class="tags">
                            ${tag_html}
                        </div>
                        <p class="time">${item.time}</p>
                    </div>    
                    `
                    }
                    else{
                        html+=`
                        <div id="span">
                            <div class="note-info-summary" onclick="start_edit('${book_title}','${item.title}');">
                                <h4>${item.title}</h4>
                                <div class="tags">
                                    ${tag_html}
                                </div>
                                <p class="time">${item.time}</p>
                            </div> 
                            <div class="del"></div>
                        </div>
                        `
                    }
                }
            })
        }
        document.getElementById('all-notes').innerHTML=html;
        document.getElementById('note-navi').innerHTML=`
            <p id="header">${book_title}</p>
            <div class="note-add">
                <p id="number">共${notes_length}条笔记</p>
                <p id="add" onclick="create_new_note('${book_title}');">新建笔记</p>
            </div>
            <div class="box">
	            <input type="text" class="input" placeholder="请输入您要搜索的笔记或标签" id="search_input">
	            <input type="button" value="search" class="button" onclick="search_note('${book_title}')">
            </div>
        `;
        if(window.screen.width<650){
            let aLi=document.querySelectorAll('#span');
            for(let i=0;i<aLi.length;i++){
                aLi[i].addEventListener("touchstart", function (e,i) {
                console.log('touchstart');
                timer = setTimeout(function () {
                     console.log('LongPress');
                     e.preventDefault();
                     let del=window.confirm('确认删除该笔记？');
                     if(del){
                        let x=e.path[1].onclick+'';
                        let r = /["|'](.*)["|']/;
                        let ans=x.match(r)[0]+'';
                        ans=ans.split(",")
                        delete_note(eval(ans[0]),eval(ans[1]));//将笔记放入回收站
                     }
                }, 800);
            });
            aLi[i].addEventListener("touchmove", function (e) {
                console.log('touchmove');
                clearTimeout(timer);
                timer = 0;
            });
            aLi[i].addEventListener("touchend", function (e) {
                console.log('touchend');
                clearTimeout(timer);
                if (timer != 0) {
                    // alert('这是点击，不是长按');
                }
                return false;
            });
          }
        }
    });
}
function delete_note(book_title,note_title){
    request('GET',`/delete-note?book_title=${book_title}&&note_title=${note_title}`);
    setTimeout(function() {
        window.location.href='/view/note-program/index.html';
    }, 100);
}
function create_new_note(book_title){
    window.location.href='/edit?book_title='+book_title;
}
function start_edit(book_title,note_title){
	window.location.href= `/edit?book_title=${book_title}&&note_title=${note_title}`;
}
function add_tags(book_title,note_title){
    let ev=window.event;
    ev.stopPropagation();
    let name=prompt("请键入要添加的标签","");
    if(name){
        request('GET',`/add-tag?book_title=${book_title}&&note_title=${note_title}&&tag_name=${name}`,null,(res)=>{
            setTimeout(function() {
                window.location.href='/view/note-program/index.html';
            }, 100);
        })
    }
    else return;
}
var arr_switch = ["笔记本","新建笔记本"];
var arr_selection = [[],[]];
window.onload=function(){
    request('OPTIONS','/notebook',null,(res)=>{
        let json=JSON.parse(res);
        json.forEach((item)=>{
            arr_selection[0].push(item['title']);
        })
        console.log(arr_selection);
    })
    var oForm = document.getElementById('form1');
    var oSwitch = oForm.children[0];
    var oSelection = oForm.children[1];
    oSwitch.onchange = function() {
        var _this = this.selectedIndex;
        // 默认进来高度清零
        oSelection.length = 0;
        initSelection(_this);
    };
    oSelection.onchange = async function(){
        await open_notebook(document.getElementById('selection').value);
    }
    oSwitch.onchange=function(){
        if(document.getElementById('switch').value==='新建笔记本'){
            new_notebook();
            document.getElementById('switch').value='笔记本';
        }
    }
    setTimeout(function() {init();}, 500);
    function init(){
        if(arr_selection[0][0]!==undefined){
            open_notebook(arr_selection[0][0]);
        }
    // 以下是移动端的笔记本初始化
        let index = 0;
        // 指定下拉的高度
        oSwitch.length = arr_switch.length;
        // 循环数组, 把内容写到下拉列表中去
        for( var i = 0; i < arr_switch.length; i++ ){
            oSwitch.options[i].text = arr_switch[i];
            oSwitch.options[i].value = arr_switch[i];
        }
        // 指定默认索引号
        oSwitch.selectedIndex = index;
        initSelection(index);
    // 以下是PC端的笔记本初始化
        let html='';
        arr_selection[0].forEach((item)=>{
            html+=`<li onclick="open_notebook('${item}');">${item}</li>`;
        })
        document.getElementById('all-notebooks').innerHTML=html;
    }
    function initSelection(index){
        oSelection.length = arr_selection[index].length;
        // 循环数组, 把内容写到ss下拉列表中去
        for( var i = 0; i < arr_selection[index].length; i++ ){
            oSelection.options[i].text = arr_selection[index][i];
            oSelection.options[i].value = arr_selection[index][i];
        }
    }
}